package com.lfg.leetcode.leetcode200;

public class No215findKthLargest {

    public static void main(String[] args) {
        int ret = findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 2);
        System.out.println(ret);
    }

    public static int findKthLargest(int[] nums, int k) {
        if (k <= 0 || nums.length == 0 || k > nums.length) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        k = nums.length - k;

        int low = 0;
        int high = nums.length - 1;
        int index = high;
        while (true) {
            while (low < high) {
                while (low < index && nums[index] >= nums[low]) {
                    low++;
                }
                swap(nums, low, index);
                index = low;


                while (index < high && nums[index] <= nums[high]) {
                    high--;
                }
                swap(nums, high, index);
                index = high;
            }
            if (index == k) {
                break;
            }
            if (index > k) {
                low = 0;
                high = index - 1;
            } else {
                low = index + 1;
                high = nums.length - 1;
            }
            index = high;
        }

        return nums[index];
    }


    public static int findKthLargest2(int[] nums, int k) {
        if (k <= 0 || nums.length == 0 || k > nums.length) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        sort(nums, k);
        for (int i = k; i < nums.length; i++) {
            if (nums[i] > nums[0]) {
                swap(nums, i, 0);
                sort(nums, k);
            }
        }
        return nums[0];
    }

    public static void sort(int[] array, int k) {
        for (int i = k / 2 - 1; i >= 0; i--) {
            adjustHeap(array, i, k);
        }

    }

    public static void adjustHeap(int[] array, int index, int length) {
        for (int k = 2 * index + 1; k > 0; ) {
            if (k + 1 < length && array[k] > array[k + 1]) {
                k += 1;
            }
            if (array[index] > array[k]) {
                swap(array, index, k);
            }
            if (index == 0) {
                break;
            }
            index = index / 2;
            k = 2 * index + 1;
        }
    }


    public static void swap(int[] array, int index1, int index2) {
        int tmp = array[index1];
        array[index1] = array[index2];
        array[index2] = tmp;
    }

}
